/* eslint-disable no-var */
import React, { useEffect, useRef } from 'react'
// 将three中所有按需导出(export)的东西都存到THREE里面,默认导出(export default)除外,√
import * as THREE from 'three'

const ThreeJSBoxGeometry = () => {
  const three = useRef(null)
  useEffect(() => {
    createThree()
  }, [])
  const createThree = () => {
    // 场景
    var scene = new THREE.Scene()
    // （透视摄像机）
    var camera = new THREE.PerspectiveCamera(
      75,
      three.current.offsetWidth / three.current.offsetHeight,
      0.1,
      1000
    )

    // 渲染器
    var renderer = new THREE.WebGLRenderer()
    // 设置渲染器的宽高
    renderer.setSize(three.current.offsetWidth, three.current.offsetHeight)
    // 放到body里面
    three.current.appendChild(renderer.domElement)

    // 生成一个立方体
    // BoxGeometry 立方体对象
    var geometry = new THREE.BoxGeometry(1, 1, 1)
    // 用于美化立方体的材质
    var material = new THREE.MeshBasicMaterial({ color: 0x00ff00 })
    // 生成一个网格,将立方体和材质放入这个网格对象中
    var cube = new THREE.Mesh(geometry, material)
    // 将网格添加到场景中
    scene.add(cube)
    // 将摄像机稍微向外移动一些
    camera.position.z = 5
    // 渲染循环 / 动画渲染
    function animate() {
      // 循环
      requestAnimationFrame(animate)
      // 动画
      cube.rotation.x += 0.01
      cube.rotation.y += 0.01
      // 生成
      renderer.render(scene, camera)
    }
    animate()
  }
  return <div ref={three} className="three-layout"></div>
}

export default ThreeJSBoxGeometry
